﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Glimpse.Core.Framework;
using GlimpseWcf.Core;
using Newtonsoft.Json;

namespace GlimpseWcf.Client
{
    public static class WcfResponseManager
    {
        public static void AddWcfResponseData(string wcfCall, WcfGlimpseResponse response, HttpContextBase context)
        {
            if (context.Items["WcfGlimpseResponses"] == null)
                context.Items["WcfGlimpseResponses"] = new Dictionary<string, Dictionary<string, object>>();

            var tabStore = ((Dictionary<string, Dictionary<string, object>>)context.Items["WcfGlimpseResponses"]);

            wcfCall = string.IsNullOrWhiteSpace(wcfCall) || tabStore.ContainsKey(wcfCall) ? "WcfTab" + (tabStore.Count + 1) : wcfCall;
            tabStore.Add(wcfCall, ConvertWcfGlimpseResponseToDictionary(response));
        }

        private static Dictionary<string, object> ConvertWcfGlimpseResponseToDictionary(WcfGlimpseResponse response)
        {
            var x = response.TabResults.ToDictionary(key => key.Name, value => JsonConvert.DeserializeObject(value.Data));
            return x;
            //return response.TabResults.Select(JsonConvert.DeserializeObject<TabResult>).ToDictionary(key => key.Name, value => value.Data);
        }

        public static Dictionary<string, Dictionary<string, object>> GetGlimpseResponsesForContext(HttpContextBase context)
        {
            return context.Items["WcfGlimpseResponses"] as Dictionary<string, Dictionary<string, object>>;
        }
    }
}
